<template>
  <el-drawer
    v-if="visible"
    :visible.sync="visible"
    :with-header="false"
    :append-to-body="true"
    size="80%"
    @close="close"
  >
    <div class="title">
      <div class="title-text">瓶批选择</div>
    </div>
    <div class="c-content">
      <el-table-form ref="form">
        <el-form-item :table-form-merge="2" class="merge-item">
          <el-select v-model="timeType" style="width: 170px; margin-right: 2px;">
            <el-option label="登记时间" value="1" />
            <el-option label="结单时间" value="2" />
          </el-select>
          <el-date-picker
            v-model="date"
            type="datetimerange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
            :clearable="false"
          />
        </el-form-item>
        <el-form-item label="所属机构：">
          <el-tree-select
            v-model="form.orgSNNo"
            clearable
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择',
              loading: $loadingPlugin.getTreeData,
            }"
            :tree-params="{
              'expand-on-click-node': false,
              'highlight-current': true,
              'filterable': true,
              props: {
                value: 'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData,
            }"
            @node-click="selectTreeChange"
          />
        </el-form-item>
        <el-form-item :table-form-merge="0.2">
          <el-checkbox v-model="form.option" label="包含下级" />
        </el-form-item>
        <template v-slot:btns>
          <el-button
            type="primary"
            @click="search"
          >查询</el-button>
        </template>
      </el-table-form>
      <div style="margin-bottom: 10px;">
        <el-button type="primary" @click="multipleImport">批量导入</el-button>
        <span style="color: red;">（批量导入功能支持一次导入多个瓶批单，导入时不支持单个充装单优惠金额的编辑修改）</span>
      </div>
      <lb-table
        ref="lbTable"
        border
        :height="358"
        element-loading-text="加载中"
        :column="userTableData.column"
        :data="userTableData.data"
        pagination
        :total="userTableData.total"
        :immediate-fetch="true"
        @fetch="getCustormerInfo"
        @selection-change="selection"
      />
    </div>
    <el-dialog title="提示" :visible.sync="dialogFormVisible" width="20%" :append-to-body="true">
      <el-form ref="dataForm" :model="form" :rules="rules">
        <el-form-item label="选择单据标签:" prop="fillingLabel" label-width="120px">
          <el-select v-model="form.fillingLabel" filterable clearable placeholder="请选择">
            <el-option
              v-for="item in fillingLabelList"
              :key="item.value"
              :label="item.keyName"
              :value="item.keyVal"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormCancel">取 消</el-button>
        <el-button type="primary" @click="dialogFormConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </el-drawer>
</template>

<script>
  import { bottleSalesQueryList, saveBatchFilling } from '@/api'
  import { csmTypeMap } from '@/utils/map'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import dayjs from 'dayjs'
  import { formatColumnMap, parseTime } from '@/utils'

  export default {
    name: 'filling-typeIn',
    props: {
      fillingLabelList: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        csmTypeMap,
        visible: false,
        dialogFormVisible: false,
        treeData: [],
        timeType: '2',
        date: [dayjs(new Date()).format('YYYY-MM-DD') + ' 00:00:00', dayjs(new Date()).format('YYYY-MM-DD') + ' 23:59:59'],
        form: {
          orgId: '',
          orgSNNo: '',
          option: false,
          fillingLabel: ''
        },
        rules: {
          fillingLabel: [{ required: true, message: '请选择单据标签', trigger: 'change' }]
        },
        paymentMethodMap: [
          { value: 1, desc: '现金', key: 'MONEY' },
          { value: 2, desc: '微信支付', key: 'WECHAT' },
          { value: 16, desc: '月结', key: 'YJ' },
          { value: 128, desc: '支付宝', key: 'ALIPAY' },
          { value: 256, desc: '预付卡', key: 'CSMCARD' },
          { value: 512, desc: '国志钱包', key: 'ICBCEPAY' },
          { value: 1024, desc: '银行支付', key: 'ICBCPAY' },
          { value: 2048, desc: '门店扫码', key: 'MDPAY' }
        ],
        selectionList: [],
        userTableData: {
          data: [],
          total: 0,
          column: [
            {
              type: 'selection'
            },
            {
              prop: 'orderCode',
              width: 160,
              label: '单号'
            //   render: (h, { row }) => (
            //   <el-link underline={false} onClick={() => this.openDetail(row)}>{row.orderCode}</el-link>
            // )
            },
            {
              prop: 'csmCode',
              label: '客户编号',
              showOverflowTooltip: true
            },
            {
              prop: 'csmName',
              label: '客户名称',
              showOverflowTooltip: true
            },
            {
              prop: 'orgName',
              width: 200,
              label: '责任机构',
              showOverflowTooltip: true
            },
            {
              prop: 'tReceivables',
              align: 'right',
              label: '订单金额'
            },
            {
              prop: 'decimalSpare1',
              align: 'right',
              label: '运费'
            },
            {
              prop: 'paymentMethod',
              label: '支付方式',
              render: (h, { row }) => (
              <span>
                {row.paymentMethod === 0
                  ? ''
                  : formatColumnMap(
                      this.paymentMethodMap,
                      'value',
                      row.paymentMethod,
                      'desc'
                    )}
              </span>
            )
            },
            {
              prop: 'tAccReceivable',
              align: 'right',
              label: '支付金额'
            },
            {
              prop: 'transactTime',
              width: 160,
              label: '登记时间',
              render: (h, { row }) => (
              <span>
                {row.transactTime &&
                  parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}:{s}')}
              </span>
            )
            },
            {
              prop: 'transactor',
              label: '登记人',
              showOverflowTooltip: true
            },
            {
              prop: 'signDt',
              width: 160,
              label: '结单时间',
              render: (h, { row }) => (
              <span>
                {row.signDt && parseTime(row.signDt, '{y}-{m}-{d} {h}:{i}:{s}')}
              </span>
            )
            },
            {
              prop: 'ownerName',
              label: '结单人',
              showOverflowTooltip: true
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 80,
              render: (h, { row, $index }) => {
                return (
                <div>
                  <el-link
                      underline={false}
                      size='mini'
                      onClick={() => this.typeIn(row, $index)}
                    >
                      导入
                    </el-link>
                </div>
              )
              }
            }
          ]
        }
      }
    },
    computed: {
      ...mapGetters(['orgList', 'userInfo'])
    },
    methods: {
      open() {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.getDetaultTreeData()
        })
      },
      // 获取所属机构数据
      async getDetaultTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
        this.form.orgId = this.userInfo.orgId
        this.form.orgSNNo = this.userInfo.orgSNNo
      },
      // 选择所属机构
      selectTreeChange(value) {
        const martchOrg = this.orgList.find((item) => item.orgSNNo === value.orgSNNo)
        // console.log('martchOrg', martchOrg)
        this.form.orgId = martchOrg.orgId
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async getCustormerInfo({ currentPage, pageSize }) {
        var query = {
          wsaleFlag: '1',
          wsaleType: '-1',
          timeType: 2,
          orderStatus: 10,
          importFillingFlag: 1,
          pageIndex: currentPage,
          pageSize: pageSize,
          ...this.form,
          orgId: this.form.option ? 0 : this.form.orgId
        }
        delete query.option
        if (this.timeType === '1') {
          if (this.date && this.date.length === 2) {
            query['transactDtStart'] = dayjs(this.date[0]).format()
            query['transactDtEnd'] = dayjs(this.date[1]).format()
          }
        } else {
          if (this.date && this.date.length === 2) {
            query['signDtStart'] = dayjs(this.date[0]).format()
            query['signDtEnd'] = dayjs(this.date[1]).format()
          }
        }
        const res = await bottleSalesQueryList(query)
        if (res && res.data) {
          this.userTableData.data = res.data.rows
          if (currentPage === 1) this.userTableData.total = res.data.total
        }
      },
      async typeIn(row) {
        this.visible = false
        row.invenBillCode = row.orderCode
        this.$emit('topingpiImport', row)
        this.date = [dayjs(new Date()).format('YYYY-MM-DD') + ' 00:00:00', dayjs(new Date()).format('YYYY-MM-DD') + ' 23:59:59']
        this.form = {
          orgId: '',
          orgSNNo: '',
          option: false
        }
        this.timeType = '2'
        this.treeData = []
        this.selectionList = []
        this.userTableData.data = []
      },
      close() {
        this.date = [dayjs(new Date()).format('YYYY-MM-DD') + ' 00:00:00', dayjs(new Date()).format('YYYY-MM-DD') + ' 23:59:59']
        this.form = {
          orgId: '',
          orgSNNo: '',
          option: false
        }
        this.timeType = '2'
        this.treeData = []
        this.selectionList = []
        this.userTableData.data = []
      },
      selection(list) {
        // console.log(list)
        this.selectionList = list.map(item => { return item.orderCode })
        // console.log(this.selectionList)
      },
      multipleImport() {
        if (!this.selectionList.length) {
          this.$message.warning('请选择导入的瓶批单')
          return
        }
        this.dialogFormVisible = true
        // this.$confirm(`确定批量导入?`, '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(async() => {
        //   const res = await saveBatchFilling(this.selectionList)
        //   if (res.data) {
        //     this.$alert(`共导入<strong>${res.data.allCount}</strong>单，成功<strong style="color:green">${res.data.succCount}</strong>单，失败<strong style="color:red">${res.data.errCount}</strong>单<br/>
        //     ${res.data.errList ? `<div style="overflow-wrap: break-word;">失败单号:<br/>${res.data.errList}</div>` : ''}`, '导入完成', {
        //       confirmButtonText: '确定',
        //       dangerouslyUseHTMLString: true
        //     })
        //     this.resolve()
        //     this.close()
        //     this.visible = false
        //   }
        // }).catch(() => {
        //   this.$message({
        //     type: 'info',
        //     message: '已取消'
        //   })
        // })
      },
      dialogFormCancel() {
        this.form.fillingLabel = ''
        this.$refs.dataForm.clearValidate()
        this.dialogFormVisible = false
      },
      dialogFormConfirm() {
        this.$refs.dataForm.validate(async(valid) => {
          if (valid) {
            const res = await saveBatchFilling({ invenBillCodeList: this.selectionList, fillingLabel: this.form.fillingLabel })
            if (res.data) {
              this.$alert(`共导入<strong>${res.data.allCount}</strong>单，成功<strong style="color:green">${res.data.succCount}</strong>单，失败<strong style="color:red">${res.data.errCount}</strong>单<br/>
            ${res.data.errList ? `<div style="overflow-wrap: break-word;">失败单号:<br/>${res.data.errList}</div>` : ''}`, '导入完成', {
              confirmButtonText: '确定',
              dangerouslyUseHTMLString: true
              })
              this.dialogFormCancel()
              this.resolve()
              this.close()
              this.visible = false
            }
          }
        })
      }
    }

  }
</script>

<style lang="scss" scoped>
/deep/.el-drawer__header {
  padding: 15px 20px;
  margin-bottom: 0;
}
.title {
  display: flex;
  padding: 20px 20px 0 20px;
  margin-bottom: 20px;
  .title-text {
    line-height: 25px;
  }
}
.c-content {
  padding: 0 20px;
  overflow-y: auto;
  font-size: 14px;
  font-weight: 400;
}
</style>
